/******
 * 1、异步更新state 吧多个state合并到一个setState
 * 2、一段时间之后清空队列渲染数组
 */
 import {renderComponent} from "../react-dom/index"
const arr = [];
//保存之前的组件
const renderQueue = [];
export function queueSetState (stateChange,component){
    if(arr.length ===0){
        defer(flush)
    }

    arr.push({stateChange,component})
    let r = renderQueue.some(item=>{
        return item === component
    })
    //第一次添加
    if(!r){
        renderQueue.push(component)
    }
}
function defer(fn){
    return Promise.resolve().then(()=>{
        fn();
    })
}
//一段时间之后
function flush(){
    debugger
    let item;
    let components;
    while(item = arr.shift()){
        const {stateChange,component} = item;

        //报存之前的状态
        if(!component.prevState){
            component.prevState = Object.assign({},component.state);
        }
        if(typeof stateChange == "function"){
            Object.assign(component.state,stateChange(component.prevState,component.props))
        }else {
            Object.assign(component.state,stateChange)
        }
        component.prevState = component.state;
    }
    //渲染有变化的组件
    while(components =renderQueue.shift()){
        renderComponent(components)
    }

}